package io.github.flylinran.modules.app.controller;

import io.github.flylinran.common.annotation.RequestLimit;
import io.github.flylinran.common.exception.BaseException;
import io.github.flylinran.common.utils.R;
import io.github.flylinran.modules.app.service.ShortenService;
import io.github.flylinran.modules.app.vo.request.ShortenQuery;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Controller
public class AppController {

    @Value("${app.host}")
    private String host;
    private final ShortenService shortenService;

    public AppController(ShortenService shortenService) {
        this.shortenService = shortenService;
    }

    @RequestMapping({"/", "index"})
    public String index() {
        return "index";
    }

    @GetMapping("/{code}")
    public void shorten(@PathVariable String code, HttpServletResponse response) {
        Optional<String> url = shortenService.findUrl(code);
        response.setStatus(301);
        response.setHeader("Location", url.orElse(host));
    }

    @RequestLimit(interval = 2)
    @RequestMapping("/shorten")
    @ResponseBody
    public R shorten(@Validated ShortenQuery query) {
        Optional<String> shortUrl = shortenService.shorten(query);
        String url = host + shortUrl.orElseThrow(() -> new BaseException("服务异常"));
        return R.ok().put("url", url);
    }
}
